package tokenparser.impl;/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2020-01-05 17:23
 * @notify
 * @version 1.0
 */
import mapping.DynamicContext;
import tokenparser.TokenHandler;
import utils.SimpleTypeRegistry;

import java.lang.reflect.Field;

public class BindingTokenParser implements TokenHandler {
    private DynamicContext context;

    public BindingTokenParser(DynamicContext context) {
        this.context = context;
    }

    /**
     * expression：比如说${username}，那么expression就是username username也就是Ognl表达式
     */
    public String handleToken(String expression) throws Exception {

        Object paramObject = context.getParam();
        if (paramObject == null) {
            throw new Exception("参数为null不能映射到${}");
        }
        String value = "";
        if (SimpleTypeRegistry.isSimpleType(paramObject.getClass())) {
            value = String.valueOf(paramObject);
        }

        Class<?> aClass = paramObject.getClass();
        Field declaredField = aClass.getDeclaredField(expression);
        declaredField.setAccessible(true);
        Object o = declaredField.get(paramObject);
        value = String.valueOf(o);

        return "'" + value + "'";


    }
}
